﻿using System.Configuration;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using InterfaceLiftLib.Configuration;
using InterfaceLiftLib.Interceptors;
using InterfaceLiftLib.Service.Implementations;
using InterfaceLiftLib.Service.Interfaces;

namespace InterfaceLiftLib.Service
{
    public static class InterfaceLiftServiceFactory
    {
        private static WindsorContainer _container;

        static InterfaceLiftServiceFactory()
        {
            InitContainer();
        }

        private static void InitContainer()
        {
            var configSection = ConfigurationManager.GetSection("InterfaceLiftService") as InterfaceLiftServiceConfigSection;
            if (configSection == null)
                throw new ConfigurationErrorsException("InterfaceLiftService configuration section not found!");

            var mashapeApiKey = configSection.MashapeApiKey;

            _container = new WindsorContainer();
            _container.Register(Component.For<IUrlBuilder>()
                                         .ImplementedBy<CamelCaseUrlBuilder>());

            _container.Register(Component.For<IHttpWebRequestBuilder>()
                                         .ImplementedBy<MashapeHttpWebRequestBuilder>()
                                         .DependsOn(Dependency.OnValue("mashapeApiKey", mashapeApiKey)));

            _container.Register(Component.For<InterfaceLiftServiceInterceptor>());

            _container.Register(Component.For<IInterfaceLiftService>()
                                         .Interceptors<InterfaceLiftServiceInterceptor>());
        }

        public static IInterfaceLiftService CreateNewService()
        {
            return _container.Resolve<IInterfaceLiftService>();
        }
    }
}
